package pure.csw.common;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;

public class ActiveMqUtils {
    public static final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Constant.URL);
    public static ThreadLocal<Connection> local = new ThreadLocal<>();
    public static Session session;
    //获取Jms Connection
    public static Connection getConnection() {
        if (local.get() == null) {
            try {
                Connection connection = factory.createConnection();
                local.set(connection);
                return local.get();
            } catch (JMSException e) {
                e.printStackTrace();
            }

        }
        return local.get();
    }
    public static Session defaultSession(){
        return getSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    //获取一次会话
    public static Session getSession(boolean transaction, int sessionAck) {
        try{
            Connection connection = local.get();
            if (connection != null) {
                session = connection.createSession(transaction, sessionAck);
            } else{
                connection = factory.createConnection();
                local.set(connection);
                session = connection.createSession(transaction, sessionAck);
            }

        }catch (Exception e) {}
        return session;
    }

}
